package com.hsjk.szwj.module.pay.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.service.WxPayService;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.module.pay.dal.dataobject.config.AbstractResp;
import com.hsjk.szwj.module.pay.dal.dataobject.config.MchAppConfigContext;
import com.hsjk.szwj.module.pay.controller.app.order.vo.UnifiedOrderReqVO;
import com.hsjk.szwj.module.pay.dal.dataobject.config.WxServiceWrapper;
import com.hsjk.szwj.module.pay.dal.dataobject.config.WxpayIsvsubMchParams;
import com.hsjk.szwj.module.pay.dal.dataobject.config.WxpayV3OrderRequestModel;
import com.hsjk.szwj.module.pay.dal.dataobject.order.PayOrderDO;
import com.hsjk.szwj.module.pay.enums.IfCodeEnum;
import com.hsjk.szwj.module.pay.enums.WxPayVersionEnum;
import com.hsjk.szwj.module.pay.util.PaywayUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @author chenjiawei
 * @desc 支付接口： 微信官方 支付方式： 自适应
 * @Date 2023/08/23 22:35
 **/
@Service
public class WxpayPaymentService extends AbstractPaymentService {
    @Resource
    private PayInterfaceDefineService payInterfaceDefineService;

    @Override
    public String getIfCode() {
        return IfCodeEnum.WXPAY.getCode();
    }

    @Override
    public boolean isSupport(String wayCode) {
        return true;
    }

    @Override
    public String preCheck(UnifiedOrderReqVO bizRQ, PayOrderDO payOrder) {
        return PaywayUtil.getRealPaywayService(this, payOrder.getWayCode())
                .preCheck(bizRQ, payOrder);
    }

    @Override
    public AbstractResp pay(UnifiedOrderReqVO bizRQ,
                            PayOrderDO payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {

        // 微信API版本

        WxServiceWrapper wxServiceWrapper =
                configContextQueryService.getWxServiceWrapper(mchAppConfigContext);

        String apiVersion = wxServiceWrapper.getApiVersion();
        if (WxPayVersionEnum.WX_V2.getVersion().equals(apiVersion)) {
            return PaywayUtil.getRealPaywayService(this, payOrder.getWayCode())
                    .pay(bizRQ, payOrder, mchAppConfigContext);
        } else if (WxPayVersionEnum.WX_V3.getVersion().equals(apiVersion)) {
            return PaywayUtil.getRealPaywayV3Service(this, payOrder.getWayCode())
                    .pay(bizRQ, payOrder, mchAppConfigContext);
        } else {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "不支持的微信支付API版本");
        }
    }
    /**
     * 构建微信统一下单请求数据
     * @param payOrder
     * @return
     */
    public WxPayUnifiedOrderRequest buildUnifiedOrderRequest(PayOrderDO payOrder,
                                                             MchAppConfigContext mchAppConfigContext) {
        String payOrderId = String.valueOf(payOrder.getId());

        // 微信统一下单请求对象
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setOutTradeNo(payOrderId);
        request.setBody(payOrder.getSubject());
        request.setDetail(payOrder.getBody());
        request.setFeeType("CNY");
        request.setTotalFee(payOrder.getAmount().intValue());
        request.setSpbillCreateIp(payOrder.getClientIp());
        request.setNotifyUrl(getNotifyUrl());
        request.setProductId(System.currentTimeMillis()+"");
        request.setTimeExpire(DateUtil.format(payOrder.getExpiredTime(),
                DatePattern.PURE_DATETIME_PATTERN));

        //订单分账， 将冻结商户资金。
        if(isDivisionOrder(payOrder)){
            request.setProfitSharing("Y");
        }

        // 特约商户
        if(mchAppConfigContext.isIsvsubMch()){
            Long ifId = payInterfaceDefineService.getIdByCode(getIfCode());
            WxpayIsvsubMchParams isvsubMchParams =
                    (WxpayIsvsubMchParams) configContextQueryService
                            .queryIsvsubMchParams(mchAppConfigContext.getMchId(),
                            mchAppConfigContext.getAppId(), ifId);
            request.setSubMchId(isvsubMchParams.getSubMchId());
            if (StringUtils.isNotBlank(isvsubMchParams.getSubMchAppId())) {
                request.setSubAppId(isvsubMchParams.getSubMchAppId());
            }
        }

        return request;
    }

    /**
     * 构建微信APIV3接口  统一下单请求数据
     * @author terrfly
     * @param payOrder
     * @return
     */
    public WxpayV3OrderRequestModel buildV3OrderRequestModel(PayOrderDO payOrder,
                                                             MchAppConfigContext mchAppConfigContext) {


        String payOrderId = String.valueOf(payOrder.getId());

        // 微信统一下单请求对象
        WxpayV3OrderRequestModel result = new WxpayV3OrderRequestModel();
        result.setOutTradeNo(payOrderId);
        result.setDescription(payOrder.getSubject());

        // 订单失效时间，遵循rfc3339标准格式，格式为yyyy-MM-DDTHH:mm:ss+TIMEZONE,示例值：2018-06-08T10:34:56+08:00
//        result.setTimeExpire(String.format("%sT%s+08:00",
//                DateUtil.format(payOrder.getExpiredTime(), DatePattern.NORM_DATE_FORMAT),
//                DateUtil.format(payOrder.getExpiredTime(), DatePattern.NORM_TIME_FORMAT)));
        DateTimeFormatter dtf = DateTimeFormatter
                .ofPattern("yyyy-MM-dd'T'HH:mm:ss+08:00")
                .withZone(ZoneId.of("Asia/Shanghai"));
        result.setTimeExpire(dtf.format(payOrder.getExpiredTime()));

        result.setNotifyUrl(getNotifyUrl(payOrderId));

        // 订单金额
        result.setAmount(new WxpayV3OrderRequestModel.Amount().setCurrency("CNY").setTotal(payOrder.getAmount().intValue()));

        // 场景信息
        result.setSceneInfo(new WxpayV3OrderRequestModel.SceneInfo().setPayerClientIp(payOrder.getClientIp()));

        //订单分账， 将冻结商户资金。
        if(isDivisionOrder(payOrder)){
            result.setSettleInfo(new WxpayV3OrderRequestModel.SettleInfo().setProfitSharing(true));
        }

        WxPayService wxPayService = configContextQueryService.getWxServiceWrapper(mchAppConfigContext).getWxPayService();

        if(mchAppConfigContext.isIsvsubMch()){
            // 特约商户
            Long ifId = payInterfaceDefineService.getIdByCode(getIfCode());
            WxpayIsvsubMchParams isvsubMchParams =
                    (WxpayIsvsubMchParams) configContextQueryService
                            .queryIsvsubMchParams(mchAppConfigContext.getMchId(),
                                    mchAppConfigContext.getAppId(), ifId);

            // 服务商相关参数
            result.setSpAppid(wxPayService.getConfig().getAppId());
            result.setSpMchid(wxPayService.getConfig().getMchId());
            result.setSubMchid(isvsubMchParams.getSubMchId());
            if (StringUtils.isNotBlank(isvsubMchParams.getSubMchAppId())) {
                result.setSubAppid(isvsubMchParams.getSubMchAppId());
            }

        }else { // 普通商户

            result.setNormalMchid(wxPayService.getConfig().getMchId());
            result.setNormalAppid(wxPayService.getConfig().getAppId());

        }

        return result;
    }
}
